package config

import (
	"cloud_worm/util/uconfig"
	"fmt"
)

type ClientConfig struct {
	Monitor			Monitor			`json:"monitor"`
	LocalConfig		LocalConfig		`json:"local_config"`
	ServerSet		ServerSet		`json:"server_set"`
}

func (c *ClientConfig) Parse(container uconfig.ConfContainer) error {
	if err := c.Monitor.parse(container); err != nil {
		return err
	}
	if err := c.LocalConfig.parse(container); err != nil {
		return err
	}
	if err := c.ServerSet.parse(container); err != nil {
		return err
	}
	return nil
}

type Monitor struct {
	CmdEnable 		bool			`json:"cmd_enable"`
	FileEnable 		bool 			`json:"file_enable"`
	LogCollector 	bool 			`json:"log_collector"`
}

func (m *Monitor) parse(container uconfig.ConfContainer) error {
	runMode := container.String("run_mode")
	if runMode == "" {
		return fmt.Errorf("no run_mode exist")
	}
	runModePrefix := runMode + "::"

	enable, err := container.Bool(runModePrefix + "monitor.cmd_enable")
	if err != nil {
		return err
	}
	m.CmdEnable = enable

	enable, err = container.Bool(runModePrefix + "monitor.file_enable")
	if err != nil {
		return err
	}
	m.FileEnable = enable

	enable, err = container.Bool(runModePrefix + "monitor.log_collector")
	if err != nil {
		return err
	}
	m.LogCollector = enable

	return nil
}

type LocalConfig struct {
	PprofEnable 	bool			`json:"pprof_enable"`
	PprofPort		string			`json:"pprof_port"`
}

func (l *LocalConfig) parse(container uconfig.ConfContainer) error {
	runMode := container.String("run_mode")
	if runMode == "" {
		return fmt.Errorf("no run_mode exist")
	}
	runModePrefix := runMode + "::"

	pprofFlag, err := container.Bool(runModePrefix + "local.pprof_enable")
	if err != nil {
		return err
	}
	l.PprofEnable = pprofFlag

	l.PprofPort = container.String(runModePrefix + "local.pprof_port")
	if l.PprofPort == "" {
		return fmt.Errorf("config 'local.pprof_port' error")
	}

	return nil
}

type ServerSet struct {
	RouterURL 		string			`json:"router_url"`
	RouterInterval 	int				`json:"router_interval"`
	AutoConfigURL 	string			`json:"auto_config_url"`
}

func (s *ServerSet) parse(container uconfig.ConfContainer) error {
	runMode := container.String("run_mode")
	if runMode == "" {
		return fmt.Errorf("no run_mode exist")
	}
	runModePrefix := runMode + "::"

	s.RouterURL = container.String(runModePrefix + "server.router_url")
	if s.RouterURL == "" {
		return fmt.Errorf("server set url config error")
	}
	routerInterval, err := container.Int(runModePrefix + "server.router_interval")
	if err != nil {
		return err
	}
	if routerInterval < 5 {
		routerInterval = 5
	}
	s.RouterInterval = routerInterval
	s.AutoConfigURL = container.String("server.auto_config_url")
	if s.AutoConfigURL == "" {
		return fmt.Errorf("config 'server.auto_config_url' error")
	}

	return nil
}
